/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import StandardTable from "@/components/StandardTable";
import ExpressInfoModal from "../../../components/ExpressInfoModal";
import { Form, Button, Row, Col, message } from 'antd';
import { debounce } from 'lodash';
import Modal from '../Modal';
import moment from "moment/moment";
import OrderDetail from '../OrderDetail'
import SearchBar from './SearchBar'

@connect(({ payment, loading }) => ({
  paymentList: payment.paymentList,
  searchFormValue: payment.searchFormValue,
  getList: loading.effects['payment/getCollectionPaymentList'],
  downloading: loading.effects['payment/getPaymentDownload']
}))
@Form.create()
class CollectionRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      title: '',
      type: null,
      expressInfo: null,  //物流信息
      showDetail: false,
      disabled: true,
      selectedRows: [],
      tableLoading: false
    };
    this.columns = [
      {
        title: '创建时间',
        key: 'create_at',
        dataIndex: 'create_at',
        align: 'center',
      },
      {
        title: '公司名称',
        key: 'company_name',
        dataIndex: 'company_name',
        align: 'center',
        render: (text, record) => {
          return (
            <a onClick={this.onTriggerModal.bind(this, true, record, 'client')}>{text}</a>
          )
        }
      },
      {
        title: '单号',
        key: 'waybill_no',
        dataIndex: 'waybill_no',
        align: 'center',
        render: (text, record) => {
          return (
            <a
              onClick={this.showExpressModal.bind(this, record)}
            >{text}</a>
          )
        }
      },
      {
        title: '揽件码',
        key: 'pickup_code',
        dataIndex: 'pickup_code',
        align: 'center',
      },
      {
        title: '代收货款金额（元）',
        key: 'collection_amount',
        dataIndex: 'collection_amount',
        align: 'center',
        render: text=><span style={{color:"red"}} >{text}</span>
      },
      {
        title: '业务员',
        key: 'collect_courier_name',
        dataIndex: 'collect_courier_name',
        align: 'center',
        render: (text,record)=>{
          return `${record.collect_courier_name}-${record.collect_courier_mobile}`
        }
      },
      {
        title: '物流状态',
        key: 'package_status',
        dataIndex: 'package_status',
        align: 'center',
        render: (text)=>{
          if( text === "-" ){
            return <span>—</span>
          }else{
            return text
          }
        }
      },
      {
        title: '回款状态',
        key: 'status',
        dataIndex: 'status',
        align: 'center',
        render: (text, record) => {
          if (record.status == 1) {
            return <span style={{ color: 'red' }}>未回款</span>
          }
          return <span>已回款</span>
        }
      },
      {
        title: '操作',
        align: 'center',
        render: (text, record) => {
          if (record.status == 2) {
            return <span>—</span>
          }
          return (
            <Button
              type='primary'
              onClick={this.onTriggerModal.bind(this, true, record, "check")}
            >核销</Button>
          )
        }
      },
      {
        title: '订单详情',
        align: 'center',
        render: (text, record) => {
          return (
            <Button
              type='primary'
              onClick={this.toggleDetail.bind(this, true, record.id)}
            >查看</Button>
          )
        }
      }
    ]
  }
  componentDidMount() {
    const { dispatch, searchFormValue } = this.props
    searchFormValue.data_start = moment(searchFormValue.data_start).format("YYYY-MM-DD")
    searchFormValue.data_end = moment(searchFormValue.data_end).format("YYYY-MM-DD")
    this.setState({tableLoading:true})
    dispatch({
      type: 'payment/getCollectionPaymentList',
      payload: {
        ...searchFormValue
      }
    }).then(()=>{
      this.setState({tableLoading: false})
    }).catch(()=>{
      this.setState({tableLoading: false})
    })
  }

  onTriggerModal(open, record, type) {
    this.formRef.props.form.resetFields()
    this.setState({
      visible: open,
      record,
      type  //区分是展示客户详情还是展示核销功能
    })
  }

  // 展示物流
  showExpressModal = data => {
    const { id, waybill_no, brand_name } = data;
    this.setState({
      expressInfo: {
        id,
        waybill_no,
        brand_name
      }
    });
  };

  modalFormRef = formRef => {
    this.formRef = formRef;
  };

  onRowSelect = (selectedRows) => {
    let disabled = selectedRows.length == 0
    this.setState({
      selectedRows,
      disabled
    })
  }

  checkBatch(){ //批量核销
    const { selectedRows } = this.state
    let nameArray = selectedRows.map(item=>{
      return item.customer_name
    })
    let isNameEqual = nameArray.every((value)=>{
      return value == nameArray[0]
    })
    if( isNameEqual ){
      this.onTriggerModal(true,selectedRows,'check')
    }else{
      message.error("请选择同一个客户进行批量核销！")
    }
  }

  cleanSelectedKeys(){
    this.setState({selectedRows: [], disabled: true})
  }

  toggleDetail = (bool,id) => {
    this.setState({
      showDetail: bool,
      detail_id: id
    })
  }

  handleStandardTableChange = debounce(pagination => {
    const { dispatch, searchFormValue } = this.props;
    const params = {
      ...searchFormValue,
      page: pagination.current,
      size: 100,
    };
    this.setState({tableLoading:true})
    dispatch({
      type: `payment/getCollectionPaymentList`,
      payload: params
    }).then(()=>{
      this.setState({tableLoading: false})
    }).catch(()=>{
      this.setState({tableLoading: false})
    });
  }, 500, {
    leading: true,
    trailing: false
  });

  render() {
    const { 
      visible, showDetail, type, 
      record, expressInfo, 
      detail_id,
      disabled, selectedRows, tableLoading
    } = this.state
    const {
      getList,
      searchFormValue,
      paymentList,
      checkDetail,
      source
    } = this.props;
    let searchVale = {...searchFormValue}

    return (
      <div style={{position:"relative"}}>
        {
          !showDetail ? (
            <>
              <SearchBar checkDetail={checkDetail} source={source}/>
              <StandardTable
                rowKey={record => record.id}
                columns={this.columns}
                data={paymentList}
                loading={tableLoading}
                selectedRows={selectedRows}
                onSelectRow={this.onRowSelect}
                onChange={this.handleStandardTableChange}
              />
              <Row style={{position:"absolute",bottom:"15px"}} >
                <Col>
                  <Button disabled={disabled} type="primary" onClick={this.checkBatch.bind(this)}>批量核销</Button>
                </Col>
              </Row>
            </>
          ) : (
            <OrderDetail id={detail_id}>
              <Button type='primary' onClick={()=>this.toggleDetail(false)}>返回</Button>
            </OrderDetail>
          )
        }
        <ExpressInfoModal
          cleanData={() => {
            this.setState({
              expressInfo: null,
            });
          }}
          data={expressInfo}
          type="payment"
        />
        <Modal
          wrappedComponentRef={this.modalFormRef}
          visible={visible}
          type={type}
          record={record}
          searchVale={searchVale}
          hideModal={() => this.onTriggerModal(false)}
          cleanSelectedKeys={ () => this.cleanSelectedKeys()}
        />
      </div>
    );
  }
}

export default CollectionRecord;